import axios from 'axios'
import { ElMessage } from 'element-plus'
import { BASE_URL } from './baseurl'
import { apiCache, debounce, cachedRequest } from './cache.js'

// 创建axios实例
const service = axios.create({
  baseURL: BASE_URL,
  timeout: 30000, // 30秒超时
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    // 添加token
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    
    // 添加请求时间戳，用于调试
    config.metadata = { startTime: new Date() }
    
    return config
  },
  error => {
    console.error('请求拦截器错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    // 计算请求耗时
    const endTime = new Date()
    const startTime = response.config.metadata?.startTime
    const duration = startTime ? endTime - startTime : 0
    
    // 记录慢请求
    if (duration > 5000) {
      console.warn(`慢请求警告: ${response.config.url} 耗时 ${duration}ms`)
    }
    
    // 处理响应数据
    const { data } = response
    
    // 如果响应成功但业务状态失败
    if (data && data.Code !== undefined && data.Code !== 200) {
      ElMessage.error(data.Message || '请求失败')
      return Promise.reject(new Error(data.Message || '请求失败'))
    }
    
    return data
  },
  error => {
    // 计算请求耗时
    const endTime = new Date()
    const startTime = error.config?.metadata?.startTime
    const duration = startTime ? endTime - startTime : 0
    
    console.error(`请求失败: ${error.config?.url} 耗时 ${duration}ms`, error)
    
    // 处理不同类型的错误
    if (error.response) {
      const { status, data } = error.response
      
      switch (status) {
        case 401:
          // 优化：只弹一次登录过期提示，关闭后跳转登录页
          if (!window.__hasShownLoginExpired) {
            window.__hasShownLoginExpired = true
            ElMessage({
              message: '登录已过期，请重新登录',
              type: 'warning',
              duration: 2000,
              onClose: () => {
                window.__hasShownLoginExpired = false
                window.location.href = '/login'
              }
            })
          }
          localStorage.removeItem('token')
          localStorage.removeItem('username')
          break
        case 403:
          ElMessage.error('权限不足')
          break
        case 404:
          ElMessage.error('请求的资源不存在')
          break
        case 500:
          ElMessage.error('服务器内部错误')
          break
        default:
          ElMessage.error(data?.Message || `请求失败 (${status})`)
      }
    } else if (error.request) {
      ElMessage.error('网络连接失败，请检查网络设置')
    } else {
      ElMessage.error('请求配置错误')
    }
    
    return Promise.reject(error)
  }
)

// 带重试的请求函数
export async function requestWithRetry(config, maxRetries = 3) {
  let lastError
  
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await service(config)
    } catch (error) {
      lastError = error
      
      // 如果是网络错误或5xx错误，才重试
      if (error.response && error.response.status >= 500) {
        console.warn(`请求失败，第 ${i + 1} 次重试:`, error.config?.url)
        // 等待一段时间再重试
        await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1)))
        continue
      }
      
      // 其他错误直接抛出
      throw error
    }
  }
  
  throw lastError
}

// 带缓存的请求函数
export async function requestWithCache(config, cacheKey, expiry = 5 * 60 * 1000) {
  return cachedRequest(
    () => service(config),
    cacheKey,
    expiry
  )
}

// 批量请求函数
export async function batchRequests(requests, batchSize = 5) {
  const results = []
  
  for (let i = 0; i < requests.length; i += batchSize) {
    const batch = requests.slice(i, i + batchSize)
    const batchResults = await Promise.allSettled(batch.map(req => service(req)))
    
    results.push(...batchResults.map(result => 
      result.status === 'fulfilled' ? result.value : null
    ))
  }
  
  return results
}

// 防抖请求函数
export const debouncedRequest = debounce((config) => service(config), 300)

// 导出默认请求函数
export default service 